# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class SinanewsPipeline:
    def process_item(self, item, spider):
        print("====生成txt文件====")
        # print(str(item['nameTitle']))
        title = item['nameTitle']
        content = item['content']
        print("====标题====" + str(title))
        print("====内容====" + str(content))

        # 在本地生成文件
        if len(item['content']) > 0:
            try:
                filename = str(item['nameTitle'][0]) + ".txt"
                fileurl = "D:/Desktop/news/" + str(item['parTitle']) + '/' + filename

                print(fileurl)
                fp = open(fileurl, "w+")
                fp.write(item['content'])
                print("生成文件成功！" + fileurl)
            except IOError:
                print("Error：没有找到文件或读取文件失败")
            except Exception:
                print("生成文件失败")
            else:
                fp.close()

        return item

